/**
 * Copyright 2014 wasu.com
 *
 *
 * Create on 2014-12-29 下午4:30:21
 */
package xj.toolkit.jms;

import java.io.UnsupportedEncodingException;

import org.apache.commons.collections4.Transformer;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import xj.toolkit.bean.CommonsHeader;
import xj.toolkit.bean.json.JSONSignal;
import xj.toolkit.bean.json.annotation.JSONMessage;
import xj.toolkit.util.Identifier;
import xj.toolkit.util.IdentifierFactory;
import xj.toolkit.util.MutableIdentifyable;

import com.alibaba.fastjson.JSON;
import com.google.common.primitives.Bytes;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Shorts;

/**
 * 将需要传输的对象转换为byte的数组。
 * 
 * @author <a href="mailto:caoxiaojian@wasu.com>xiaojian.cao</a>
 * 
 */
public class Msg2BytesTransformer implements Transformer<JSONSignal, byte[]> {

	private static final Logger logger = LoggerFactory.getLogger(Msg2BytesTransformer.class);

	/**
	 * @see stc.skymobi.util.Transformer#transform(java.lang.Object)
	 */
	@Override
	public byte[] transform(JSONSignal msg) {
		JSONMessage jm = msg.getClass().getAnnotation(JSONMessage.class);
		if (jm == null) {
			throw new RuntimeException("invalid json message, missing @JSONMessage.");
		}

		final Identifier<?> id = ((MutableIdentifyable) msg).getIdentification();
		if (logger.isDebugEnabled()) {
			logger.debug("encoding JSONObject {} to wrappedBuffer", msg);
		}
		if (null != id) {
			final String jsonString = JSON.toJSONString(msg);
			byte[] jsonBytes = null;
			try {
				jsonBytes = jsonString.getBytes("UTF-8");
			} catch (UnsupportedEncodingException e) {
				logger.error("Unsupport encoding['utf-8'].", e);
				return null;
			}

			CommonsHeader header = new CommonsHeader();
			header.setMessageCode(jm.messageCode());
			header.setMessageLength(jsonBytes.length);
			
			byte[] idContent = IdentifierFactory.gerIdByte(id);
			header.setIdBytesLen(Shorts.fromBytes(idContent[0], idContent[1]));
			header.setIdBytes(ArrayUtils.subarray(idContent, 2, idContent.length));
			

			return Bytes.concat(new byte[header.getBasicVer()], Shorts.toByteArray(header.getPayloadType()),
					Shorts.toByteArray(header.getType()), idContent, Ints.toByteArray(header.getReserved()),
					Ints.toByteArray(header.getMessageCode()), Ints.toByteArray(header.getMessageLength()), jsonBytes);
		}

		if (logger.isWarnEnabled()) {
			logger.warn("{} is json but missing transactionId", msg);
		}

		return null;
	}

}
